<?php

namespace app\controller;

use app\model\Tweet;
use app\model\User;
use core\Event;

class TweetController extends BaseController
{
    /**
     * 创建一个新的推文或回复
     */
    public function create(): void
    {
        $this->requireLogin();

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $content = trim($_POST['content'] ?? '');
            $parentId = !empty($_POST['parent_id']) ? (int)$_POST['parent_id'] : null;

            if (!empty($content)) {
                $tweet = Tweet::create([
                    'user_id' => $this->getCurrentUserId(),
                    'content' => $content,
                    'timestamp' => time(),
                    'parent_id' => $parentId,
                ]);

                // 如果是回复，则分发事件
                if ($parentId !== null) {
                    $originalTweet = Tweet::find($parentId);
                    $replyingUser = User::find($this->getCurrentUserId());

                    if ($originalTweet && $replyingUser) {
                        Event::dispatch('tweet.replied', $originalTweet, $replyingUser);
                    }
                }
            }
        }

        $this->redirect($_SERVER['HTTP_REFERER'] ?? '/');
    }

    /**
     * 查看单个推文及其回复
     * @param int $id
     */
    public function view(int $id): void
    {
        $this->requireLogin();

        $mainTweet = Tweet::find($id);

        if (!$mainTweet) {
            http_response_code(404);
            echo "Tweet not found";
            return;
        }

        $replies = $mainTweet->replies();

        $this->render('tweet/view', [
            'mainTweet' => $mainTweet,
            'replies' => $replies
        ]);
    }
}
